import numpy as np
import dlib
import cv2
import xml_functions as rx
import face_recognition

FACIAL_LANDMARKS_68_IDXS = dict([
	("mouth", (48, 68)),
	("right_eyebrow", (17, 22)),
	("left_eyebrow", (22, 27)),
	("right_eye", (36, 42)),
	("left_eye", (42, 48)),
	("nose", (27, 36)),
	("jaw", (0, 17))
])

def shape_to_np(shape, dtype="int"):
	# 创建68*2
	coords = np.zeros((shape.num_parts, 2), dtype=dtype)
	# 遍历每一个关键点
	# 得到坐标
	for i in range(0, shape.num_parts):
		coords[i] = (shape.part(i).x, shape.part(i).y)  # 第i个关键点的横纵坐标。
	return coords

def visualize_facial_landmarks(image, shape, colors=None, alpha=0.75):
	# 创建两个copy
	# overlay and one for the final output image
	overlay = image.copy()
	output = image.copy()
	# 设置一些颜色区域
	if colors is None:
		colors = [(19, 199, 109), (79, 76, 240), (230, 159, 23),
			(168, 100, 168), (158, 163, 32),
			(163, 38, 32), (180, 42, 220)]
	# 遍历每一个区域
	for (i, name) in enumerate(FACIAL_LANDMARKS_68_IDXS.keys()):
		# 得到每一个点的坐标
		(j, k) = FACIAL_LANDMARKS_68_IDXS[name]
		pts = shape[j:k]
		# 检查位置
		if name == "jaw":
			# 用线条连起来
			for l in range(1, len(pts)):
				ptA = tuple(pts[l - 1])
				ptB = tuple(pts[l])
				cv2.line(overlay, ptA, ptB, colors[i], 2)
		# 计算凸包
		else:
			hull = cv2.convexHull(pts)
			cv2.drawContours(overlay, [hull], -1, colors[i], -1)
	# 叠加在原图上，可以指定比例
	cv2.addWeighted(overlay, alpha, output, 1 - alpha, 0, output)
	return output

def getEasyBox(frame):
    padding = int(frame.shape[1]/10.8)
    box = dlib.rectangle(padding,padding,frame.shape[1]-padding, frame.shape[0]-padding)
    return box

MP4NAME = 'VID_20211206_170004'
URL = "rtsp://admin:admin@192.168.31.173:8554/live"

def openMp4():
    """打开视频"""
    #获得视频的格式
    videoCapture = cv2.VideoCapture('./'+MP4NAME+'.mp4')
 
    #获得码率及尺寸
    fps = videoCapture.get(cv2.CAP_PROP_FPS)#获取实时帧率
    size = (int(videoCapture.get(cv2.CAP_PROP_FRAME_WIDTH)),
            int(videoCapture.get(cv2.CAP_PROP_FRAME_HEIGHT)))
    fNUMS = videoCapture.get(cv2.CAP_PROP_FRAME_COUNT)#获取总帧数
    
    success, frame = readNewFrame(videoCapture)
    return videoCapture,fps,size,fNUMS,success, frame

def closeMp4(video):
    """关闭视频"""
    video.release()
    cv2.destroyAllWindows()
    
def showMp4(frame):
    """显示一帧的图像"""
    cv2.imshow('windows', frame) #显示
    cv2.waitKey(int(1000/int(fps))) #延迟

def readNewFrame(video):
    """读取下一帧"""
    success, frame = video.read()
    return success, frame

def BeginIPCamera():
    """开始执行网络摄像头捕捉"""
    #cap = openIPCamera()
    # 加载人脸检测与关键点定位
    detector = dlib.get_frontal_face_detector()
    predictor = dlib.shape_predictor('shape_predictor_68_face_landmarks.dat')
    cap = cv2.VideoCapture(URL)#读取视频流
    while(cap.isOpened()):
        ret, frame = cap.read()
        # 人脸检测
        rects = detector(frame)
        # 遍历检测到的框
        for (_, rect) in enumerate(rects):
            # 对人脸框进行关键点定位
            # 转换成ndarray
            print(rect)
            shape = predictor(frame, rect)
            shape = shape_to_np(shape)
            # 根据位置画点
            for (x, y) in shape:
                cv2.circle(frame, (x, y), 3, (0, 0, 255), -1)
            cv2.imshow('frame',frame)
        if not rects:
            cv2.imshow('frame',frame)
            print("未找到人脸")
        if cv2.waitKey(1) & 0xFF == ord('q'):
            break
        
    cap.release()
    cv2.destroyAllWindows()

def BeginIPCamera2():
    """开始执行网络摄像头捕捉"""
    #face_recognition
    cap = cv2.VideoCapture(URL)#读取视频流
    while(cap.isOpened()):
        ret, frame = cap.read()
        # 人脸检测
        face_landmarks_list = face_recognition.face_landmarks(frame)
        if len(face_landmarks_list) == 1:
            for i in face_landmarks_list[0]:
                for s in face_landmarks_list[0][i]:
                    cv2.circle(frame, (s[0], s[1]), 3, (0, 0, 255), -1)
        cv2.imshow('frame',frame)
        if cv2.waitKey(1) & 0xFF == ord('q'):
            break
        
    cap.release()
    cv2.destroyAllWindows()
"""
# 加载人脸检测与关键点定位
detector = dlib.get_frontal_face_detector()
predictor = dlib.shape_predictor('shape_predictor_68_face_landmarks.dat')
# 加载视频
videoCapture,fps,size,fNUMS,success, frame = openMp4()
#图片缩放尺寸
(h, w) = frame.shape[:2]
width=354
r = width / float(w)
dim = (width, int(h * r))
a = 0
while success :
    # 读取输入数据，预处理
    frame = cv2.resize(frame, dim, interpolation=cv2.INTER_NEAREST)
    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)

    # 人脸检测
    rects = detector(gray, 1)
    # 遍历检测到的框
    for (_, rect) in enumerate(rects):
        # 对人脸框进行关键点定位
        # 转换成ndarray
        print(rect)
        shape = predictor(gray, rect)
        shape = shape_to_np(shape)
        print(a)
         # 根据位置画点
        for (x, y) in shape:
            cv2.circle(frame, (x, y), 3, (0, 0, 255), -1)
        showMp4(frame)
        images_path = 'images/' + MP4NAME + '_frame' + str(a) + '.jpg'
        cv2.imwrite(images_path, frame)
        rect = getEasyBox(frame)
        print(rect)
        print("----------")
        rx.appendXML(shape,rect,images_path,'my2_source.xml')
    a = a + 1
    for i in range(30):#跳帧取图
        success, frame = readNewFrame(videoCapture) #获取下一帧


closeMp4(videoCapture)
"""

BeginIPCamera2()